package com.hyh.fireworks.common.service.impl;

import com.hyh.fireworks.common.service.ICommonService;
import com.hyh.fireworks.common.utils.FileUploadUtil;
import com.hyh.fireworks.config.FireworksProperties;
import com.hyh.fireworks.exception.file.FileException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 通用服务类
 *
 * @author Summerday
 */

@Service
@Slf4j
public class CommonServiceImpl implements ICommonService {

    @Resource
    FireworksProperties fireworksProperties;

    private String getUploadDir() {
        return fireworksProperties.getUploadDir();
    }


    @Override
    public String upload(MultipartFile file) {
        // 获取上传路径
        String uploadDir = getUploadDir();
        log.info("上传路径为 : {}", uploadDir);
        String fileName;
        try {
            fileName = FileUploadUtil.upload(uploadDir, file);
        } catch (IOException e) {
            throw new FileException(e.getMessage());
        }
        log.info("返回文件名为 : {}", fileName);
        return "/upload/" + fileName;
    }

    @Override
    public String upload(MultipartFile file, String[] extension) {
        // 获取上传路径
        String uploadDir = getUploadDir();
        log.info("上传路径为 : {}", uploadDir);
        String fileName;
        try {
            fileName = FileUploadUtil.upload(uploadDir, file, extension);
        } catch (IOException e) {
            throw new FileException(e.getMessage());
        }
        log.info("返回文件名为 : {}", fileName);
        return "/upload/" + fileName;
    }
}
